package com.qfedu.entity.chapter2.course08;

import java.util.Map;
import java.util.TreeMap;

public class Client {

    public static void main(String[] args) {
//        //物理节点
//        List<String> ipNodes = List.of("192.168.1.101", "192.168.1.102", "192.168.1.103", "192.168.1.104");
//        // 统计 每个真实节点复制100个虚拟节点情况下，0-65536个对象在4台服务器的分布情况
//        ConsistentHash<String> consistentHash = new ConsistentHash<>(100, ipNodes);
//        statistics(consistentHash, 0, 65536);
//        // 统计 每个真实节点复制10000个虚拟节点情况下，0-65536个对象在4台服务器的分布情况
//        consistentHash = new ConsistentHash<>(10000, ipNodes);
//        statistics(consistentHash, 0, 65536);
    }

    private static void statistics(ConsistentHash<String> consistentHash, int objectMin,
                                   int objectMax) {
        Map<String, Integer> objectNodeMap = new TreeMap<>(); // IP => COUNT
        for (int object = objectMin; object <= objectMax; object++) {
            //遍历各个对象存储的节点ip
            String nodeIp = consistentHash.get(Integer.toString(object));
            Integer count = objectNodeMap.getOrDefault(nodeIp, 0);
            //统计各个ip缓存的对象数量
            objectNodeMap.put(nodeIp, count + 1);
        }

        // 打印
        double totalCount = objectMax - objectMin + 1;
        String label = "统计";
        System.out.println("======== " + label + " ========");
        for (Map.Entry<String, Integer> entry : objectNodeMap.entrySet()) {
            long percent = (int) (100 * entry.getValue() / totalCount);
            System.out.println("IP=" + entry.getKey() + ": RATE=" + percent + "%");
        }
    }

}